package com.umeox.moto.common.utils;


import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtils {

    public static boolean isEmpty(String input) {
        return input == null || input.trim().length() == 0 || isSpace(input);
    }

    public static boolean isSpace(final String s) {
        if (s == null) {
            return true;
        }
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 正则表达式验证文件下载地址是否合法
     */
    public static boolean isUrl(String str) {
        if (isEmpty(str)) {
            return false;
        }
        String regex = "^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }


    /**
     * 从URL下载地址中，截取文件名带后缀
     */
    public static String getFileNameWithSuffix(String url, String def) {
        try {
            if (isUrl(url)) {
                int lastIndexSlash = url.lastIndexOf("/");
                if (lastIndexSlash < 0) {
                    return def;
                }

                String name = def;
                try {
                    name = url.substring(lastIndexSlash + 1);
                } catch (Exception ignored) {
                }
                return name;
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 从文件下载地址获取文件后缀
     */
    public static String getSuffix(String url) {
        try {
            if (isUrl(url)) {
                String[] urlSegments = url.split("\\.");
                return urlSegments[urlSegments.length - 1];
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


}